import 'package:flutter/material.dart';

class Test extends StatefulWidget {
  const Test({super.key});
  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {
  final ScrollController _scrollController = ScrollController();
  List<Widget> cityNames = List.generate(
    10,
    (index) => ListTile(
    leading: Icon(Icons.safety_check),
    title: Text('fact_check_outlined ${index}'),
    subtitle: Text('子标题'),
    trailing: Icon(Icons.keyboard_arrow_right),
  ));
  @override
  void initState() {
    _scrollController.addListener(() {
      if(_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        _loadData();
      }
    });
    // TODO: implement initState
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    const title = '列表下拉刷新上拉加载';
    return Scaffold(
      // appBar: AppBar(title: Text(title),),
      body: RefreshIndicator(
        onRefresh: handleRefresh,
        child: ListView.builder(
          // 绑定滚动的_scrollController 监听滚动事件
          controller: _scrollController,
          itemCount: cityNames.length,
          itemBuilder: (BuildContext context, int index) {
            return cityNames[index];
          },
        ),
    ));
  }

  // _buildList() {
  //   return cityNames.map((e) => _item(e)).toList());
  // }
  // Widget _item(String city) {
  //   return Container(
  //     height: 88,

  //   );
  // }

  Future<void> handleRefresh() async {
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      cityNames = cityNames.reversed.toList();
    });
  }
  
  void _loadData() async{
    await Future.delayed(Duration(microseconds: 200));
    setState(() {
      List<Widget> list = List<Widget>.from(cityNames);
      list.addAll(cityNames as Iterable<Widget>);
      cityNames = list.cast<Widget>();
    });
  }
}
